<?php

/* 
 * 商家模型
 * @author wyb
 */
namespace DataAPI\Model;
use Common\Controller\OdooApiController;



class ErpApiModel extends ApiModel {
   public $username='';
   public $password='';
   public $method='';
   public $data=array();
   function __construct()
   {   
     
       $this->url="http://api.newbeemall.com/v1.0/rest";
       $this->username='w3yun'; 
       $this->password='58d3ed00-6e6c-11e6-8305-080027866ab0';   
      // $this->username='ok'; 
      // $this->password='python'; 
	   $this->odooerp = new OdooApiController();
	   ///默认连接B仓
	   $this->odooerp->_initializeB();
        
	  
   }
   
   

   public function supplier_add($id=1)
   {
	   $this->__construct();
	   $modol=M('suplier');
	   $data=$modol->where("erp_id is null or erp_id =''")->limit(1)->find();
	   $data['username']=$this->username;
	   $data['passwd']=$this->password;
	   $data['method']='erp.supplier.add';
	   $data['phone']=$data['tel'];
	  
        $spid=$data['id'];
	  ///过滤掉无需提交的数据
	  unset ($data['user']);
	  unset ($data['tel']);
	  unset ($data['id']);
	  unset ($data['erp_id']);
	 
	  
	  //var_dump($data);
      
	  $result=$this->post_json($this->url,$data);
	  ///$result->error_response
	  //echo "<br>";
	  $re=json_decode($result);
	  //echo $re->erp_supplier_add_response->data;
	  ///回写供应商ID
      if(is_int($re->erp_supplier_add_response->data))
	  {
		  $da['id']=$spid;
		  $da['erp_id']=$re->erp_supplier_add_response->data;
		  $modol->where('id='.$spid)->data($da)->save();
		  echo "saved erpid <br>";
	  };
	  //var_dump($result);
	  ////继续处理未处理完成的
	  //if($data&&is_int($re->erp_supplier_add_response->data))
	   //echo '<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),3000)</script><br>';
      
	   
   }
   
   ////处理仓库自动确认的单子
   public function autopickB()
   {
	   $this->__construct(); //默认连接B仓
	   $erpstockx=$this->odooerp->autopick(13092);
	   echo $erpstockx;
	   if($erpstockx>0)
	   {
		    echo "下架确认剩余".$erpstockx."条。";
		    echo '<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),3000)</script><br>';
			die();
		   
	   }else
	   {
		  $erpstockx= $this->odooerp->autobozhong();
		  if($erpstockx>0)
	      {
		    echo "播种确认剩余".$erpstockx."条。";
		    echo '<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),3000)</script><br>';
			die();
		  }
	   };
	   
	   echo "<br>全部运行完成。<br>";
	   
	   
   }
   public function get_order($out_sn='',$buyer='')
   {
	   /// erp 订单获取
	   
	   $this->__construct();
	   $ds['username']=$this->username;
	   $ds['passwd']=$this->password;
	   $ds['method']='erp.tradeOrder.get';
	   $ds['order']=$out_sn;
	   $ds['order']=$buyer;
	   $result=$this->post_json($this->url,$ds);
	   
	   var_dump($result);
	   
   }
   
   
      public function erp_hsTaxRate_get ($sku='')
   {
	   
	   
	   $this->__construct();
	   $ds['username']=$this->username;
	   $ds['passwd']=$this->password;
	   $ds['method']='erp.hsTaxRate.get';
	   $ds['sku']=$sku;
	   $re=$this->post_json($this->url,$ds);
	   
	  
	   
   }
 
   
   	public function autoStockAll()
	{
		///需要contrl类运行
		$this->autoStock();
		echo '<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),3000)</script><br>';
	}
	
	public function autoStock()
	{
	   ////心蜜蜂供应商ID为137 从B仓获取
	   $goods=M('goods')->field('id,sku,stock_num,stock_refresh')->where("supply_id=137")->order('stock_refresh ASC')->find();
 
	   if((time()-$goods['stock_refresh'])<300) die();

 
 
	   $this->odooerp->_initializeB();
	   
	   $localstock=$goods['stock_num'];
	   $erpstockx=$this->odooerp->readbySku($goods['sku']);
	   $erpstockd=$erpstockx[0];
	   $erpstock=$erpstockd['qty_available'];
	   
	   
	   echo $erpstock."==".$localstock;
       
	   if($erpstock!=$localstock)
       {   
	     $goods['stock_num']=$erpstock;
         $change['sku']=$goods['sku'];
         $change['local']=$localstock;
         $change['remote']=$erpstock;
         $change['from']='6B';
         $change['refresh']=time();
		 M('goods_stock_change')->add($change);
	   }
		
       $goods['stock_refresh']=time();
	   M('goods')->where('id='.$goods['id'])->save($goods);   
	   return $goods['id']."refresh stock to".$erpstock ;
	}
	
	public function test_inventory()
	{
		
		$this->odooerp->_initializeB();
		$ids=$this->odooerp->test_inventory();
	}
	public function pancunsyn()
	{
		///盘存相当于分拣操作-统一到分拣操作
		$runnum=0;
	   $maxnum=5;
	  
		$order=M('stock_picking');
		$this->odooerp->_initializeB();
	    ///存储到临时数值
	    if(count($_SESSION['TMP_PICKIDS_P'])==0||!isset($_SESSION['TMP_PICKIDS_P']))
		{
			 $ids=$this->odooerp->getpancunids();
			 //var_dump($ids);
			 $_SESSION['TMP_PICKIDS_P']=$ids;
		}else
		{
			$ids=$_SESSION['TMP_PICKIDS_P'];
		}
		$idstring=implode(",",$ids);
		///盘存的pick type设置为0
		$eids=$order->field('flag')->where("pick_type=0 and stock='6B' and flag in (".$idstring.")")->select();
	    $eds=array();
		foreach($eids as $e)
		{
			$eds[]=(int)$e['flag'];
		}
		 
  
		$ids=array_diff($ids,$eds);
		 //var_dump($ids);
        // $ids=array();
		// $ids[]=8;
        //die();
		
	    echo "pancun :".count($ids)."  to process.<br>";
	 
		 foreach($ids as $k =>$id)
	   {
		 if($runnum>$maxnum)
		 {
			echo 'waiting for next refresh 3:'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),5000)</script><br>';
			die(); 
		 }
		 $data=$this->odooerp->readpancun($id);
		
		//var_dump($data);die();
		 if($data['id']<=0) 
		 {
			 var_dump($data);
			 echo "123".$data['id']."id=".$id;
			 die();
		 }
		 $order=array();
		$order['pick_id']='pancun-6B-'.$data['id'];
	    $order['oper']=$data['write_uid'][1];
		echo "process :".$data['origin']." .<br>";
		if(strpos($data['origin'],"||")>0)
		{
			$to=explode($data['origin']);
			$data['origin']=$to[1];
		}
		
	    $order['poname']=$data['origin'];
	    $order['date']=strtotime($data['date']);
	    $order['state']=substr($data['state'],0,10);
	    $order['location_id']=$data['location_id'][0];
	    $order['location_dest_id']=$data['location_dest_id'][0];
	    $order['qty']=$data['to_do'];
	    $order['qty_done']=$data['have_do'];
	    $order['pick_type']=0;
	    $order['stock']='6B';
	    $order['flag']=$data['id'];
		 
		 
		 $lines=$data['move_ids'];
		 if(count(lines)==0){echo "cant find lines.<br>";die();} 
		 $linedata=$this->odooerp->readstockmovelines($lines);
		 
		 $order['lines']=array();
		    foreach($linedata as $i =>$l)
			{  
				$line=array();
				preg_match("/\[(P\d+)\](.+)/", $l['product_id'][1], $pd);
				$line['sku']=$pd[1];
				$line['date']=strtotime($l['write_date']);
				$line['location_id']=$l['location_id'][0];
				$line['location_dest_id']=$l['location_dest_id'][0];
				$line['procure_method']=$l['procure_method'];
				$line['state']=substr($l['state'],0,12);
				$line['picking_id']=$order['pick_id'];
				$line['qty']=$l['product_qty'];
				$order['lines'][$i]=$line;
			}
        ///add here
		echo "add started.";
		addstockpicking($order);
		$runnum++;
		//die();
	   }
	}
	
	public function stockpickingsyn()
	{
		
	   $runnum=0;
	   $maxnum=5;
	  
		$order=M('stock_picking');
	    ///存储到临时数值
	    $this->odooerp->_initializeB();
        if(count($_SESSION['TMP_PICKIDS'])==0||!isset($_SESSION['TMP_PICKIDS']))
		{
			
			 $ids=$this->odooerp->getpickingids();
			 $_SESSION['TMP_PICKIDS']=$ids;
		}else
		{
			$ids=$_SESSION['TMP_PICKIDS'];
		}
	 

	    $idstring=implode(",",$ids);
		$eids=$order->field('flag')->where("pick_type>0 and flag in (".$idstring.")")->select();
	    $eds=array();
		foreach($eids as $e)
		{
			$eds[]=(int)$e['flag'];
		}
		 
  
		$ids=array_diff($ids,$eds);
		 //var_dump($ids);

        //die();
	    echo "stockpicking :".count($ids)."  to process.<br>";
		//$ids=array();
		///$ids[]=1018;
		
		//var_dump($ids);
	   foreach($ids as $k =>$id)
	   {
		 if($runnum>$maxnum)
		 {
			echo 'waiting for next refresh 3:'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),5000)</script><br>';
			die(); 
		 }
		 $data=$this->odooerp->readstockpicking($id); 
		 
		
		 if($data['id']<=0) 
		 {
			 var_dump($data);
			 echo "123".$data['id']."id=".$id;
			 die();
		 }
		 $order=array();
		$order['pick_id']='pick-6B-'.$data['id'];
	    $order['oper']=$data['write_uid'][1];
		echo "process :".$data['origin']." .<br>";
		if(strpos($data['origin'],"||")>0)
		{
			$to=explode($data['origin']);
			$data['origin']=$to[1];
		}
	    $order['poname']=$data['origin'];
	    $order['date']=strtotime($data['date']);
	    $order['state']=substr($data['state'],0,12);
	    $order['location_id']=$data['location_id'][0];
	    $order['location_dest_id']=$data['location_dest_id'][0];
	    $order['qty']=$data['to_do'];
	    $order['qty_done']=$data['have_do'];
	    $order['pick_type']=$data['picking_type_id'][0];
	    $order['stock']='6B';
	    $order['flag']=$data['id'];
		
		
		 $lines=$data['move_lines'];
		 if(count(lines)==0){echo "cant find lines.<br>";die();} 
		 $linedata=$this->odooerp->readstockmovelines($lines);
		 
		 $order['lines']=array();
		    foreach($linedata as $i =>$l)
			{
				$line=array();
				preg_match("/\[(P\d+)\](.+)/", $l['product_id'][1], $pd);
				$line['sku']=$pd[1];
				$line['date']=strtotime($l['write_date']);
				$line['location_id']=$l['location_id'][0];
				$line['location_dest_id']=$l['location_dest_id'][0];
				$line['procure_method']=$l['procure_method'];
				$line['state']=substr($l['state'],0,12);
				$line['picking_id']=$order['pick_id'];
				$line['qty']=$l['product_qty'];
				$order['lines'][$i]=$line;
			}
		
	
		 addstockpicking($order,$msg);

		 $runnum++;
		 //var_dump($order);
		 
		
		 
	   }
	    if(count($_SESSION['TMP_PICKIDS'])<$runnum) exit();
	    echo  'waiting for next refresh2:'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),3000)</script><br>';
	}
	
    ///jjqd 同步中台
	public function transordersyn(){
	   
	  $stime=microtime(true);
	  $runnum=1;
	  $modelorder=M('transorder');
	  $ids=$this->odooerp->getjjqdlist();
	  
	  ///过滤已经读取的ids
	  //var_dump($ids);
	   foreach($ids as $k =>$id)
	 {
		 $od=$modelorder->where(array('flag_id'=>$id))->find();
		// var_dump($od);
		 if($od) unset($ids[$k]);
	 }
	   foreach($ids as $k =>$id)
	 {
		if($runnum>5){
		 echo "run time:".(microtime(true)-$stime)."<br/>";
		 if($ids)
	     {
			 echo  'waiting for next refresh'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),3000)</script><br>';
		 }
		 return false; 
	    } 
		
		$data=$this->odooerp->readtransorder($id);  ////jjqd读取
		$order=array();
		$order['poname']=$this->getPOnameByflagid($data['pur_lines'][0]);
	    $order['toname']=$data['name'];
	    $order['desc']=$data['pur_description'];
	    $order['supplier']=mb_convert_encoding($data['partner_id'][1], "html-entities","utf-8" );
	    $order['ttime']=strtotime($data['date']);
	    $order['state']=substr($data['state'],0,12);
	    $order['warehouse_code']=$data['warehouse_id'][1];
	    $order['oper']=$data['write_uid'][1];
		$order['flag_id']='erp'+$data['id'];
        $lines=$data['order_lines'];
		$linedata=$this->odooerp->readjjqdlines($lines);   ////jjqd详情
		
		//var_dump($linedata);
		$order['lines']=array();
		    foreach($linedata as $i =>$l)
			{
				$line=array();
				preg_match("/\[(\d+)\](.+)/", $l['code_ts'][1], $pd);
				$line['declare_content']=$l['declare_content'];
				$line['curr']=$l['curr'][1];
				$line['declare_unit']=$l['declare_unit'][1];
				$line['qty']=$l['product_qty'];
				$line['sku']=$l['cop_g_no'];
				$line['ts_code']=$pd[1];
				$line['ts_name']=$pd[2];
				$line['toname']=$data['name'];
				$line['flag']=$l['id'];
				$line['from_flag']='erp';
				$line['loc_price']=$l['local_price'];
				$line['curr_price']=$l['ch_price'];
				$line['gross_weight']=$l['gross_weight'];
				$line['product_variant']=mb_convert_encoding($l['product_variant'], "html-entities","utf-8" );
				$line['curr_amount']=$l['amount_total'];
				$line['loc_amount']=$l['local_amount'];
				$line['weight']=$l['weight'];
				
				
				$order['lines'][$i]=$line;
			}
			
			addtransorder($order);
		    $runnum=$runnum+1;
		 
		 
	 }
	 
	}
	
   public function getPOnameByflagid($id)
   {
	   $modelorder=M('purchorder');
	   $po=$modelorder->where(array('flag'=>$id))->find();
	   //var_dump($po);
	   if($po)
	   {
		   return $po['poname'];
	   }else
	   {
		   return false;
	   }   
	   
   }
   
   function characet($data){
	  if( !empty($data) ){
	    $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ;
	    if( $fileType != 'UTF-8'){
	      $data = mb_convert_encoding($data ,'utf-8' , $fileType);
	    }
	  }
	  return $data;
	}
   ////已经确认采购单同步
   public function purchordersyn(){
	 
	 

	 $stime=microtime(true);
	 $runnum=1;
	 $modelorder=M('purchorder');
	//$modelline=M('purchorder_line');
	 $ids=$this->odooerp->readallpurchaseids();
	  
	 foreach($ids as $k =>$id)
	 {
		 $od=$modelorder->where("from_flag='erp' and flag=".$id)->find();
		 if($od) unset($ids[$k]);
	 }
 
	 foreach($ids as $k =>$id)
	 {
	   if($runnum>10){
		 echo "run time:".(microtime(true)-$stime)."<br/>";
		  echo  'waiting for next refresh'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),3000)</script><br>';
		 return false; 
	  } 
	$data=$this->odooerp->readpurchase($id);
	
	//仓位关系对应
	if($data['warehouse_id'][0]==1)$warehouse='6B';
	if($data['warehouse_id'][0]==2)$warehouse='4H';
	if($data['warehouse_id'][0]==3)$warehouse='VM';
	if($data['warehouse_id'][0]==4)$warehouse='YZC';
	if($data['location_id'][0]==55)$warehouse='4H';
	//if($data['warehouse_id'][0]==4)$warehouse='YZC';
	//if($data['warehouse_id'][0]==4)$warehouse='YZC';
	//if($data['warehouse_id'][0]==4)$warehouse='YZC';
	
	//var_dump($data);
    echo "process purchoreder:".$data['name']."<br>";
	$order=array();
	$order['poname']=$data['name'];
	$order['desc']=$data['description'];
	$order['ptime']=strtotime($data['date_order']);
	$order['supplier']=$data['partner_id'][1]; //需要转换
	$order['pick_id']=0;
	$order['trade_type']=$data['classify'];
	$order['courty']=$data['currency_id'][1];
	$order['untax_amount']=round($data['untax_amount']/$data['currency_rate'],2);
	$order['amount']=round($data['amount_untaxed']/$data['currency_rate'],2); ///转换为本币金额
	$order['curr']=$data['currency_id'][1];
	$order['curr_rate']=$data['currency_rate'];
	$order['state']=substr($data['state'],0,12);
	$order['compay']=$data['company_id'][1]; ///采购企业
	$order['flag']=$data['id'];
	$order['from_flag']='ERP';
	$order['oper']=$data['write_uid'][1];
	$order['warehouse']=$warehouse;
	$warehouse='';
	
	///order_line
	    $lines=$data['order_line'];
		//var_dump($lines);die();
		$orderline=$this->odooerp->readpurchlines($lines);
		
		$order['line']=array();
		foreach($orderline as $k =>$ol)
		{
			
			$line=array();
            // echo $ol['product_id'][1]."<br/>";
			$line['hash']=md5('ERP-'.$ol['id']); ////定义一个唯一性标识
			//$ol['product_id'][1]= mb_convert_encoding($ol['product_id'][1], "html-entities","utf-8" );
			preg_match("/\[(P\d+)\](.+)/", $ol['product_id'][1], $pd);
		    //echo $ol['product_id'][1];
			$line['poname']=$data['name'];
			$line['sku']=$pd[1];
			$line['name']=substr($pd[2],0,152);
			$line['earn13']=$ol['ean13'];
			
			$line['lstprice']=$ol['lst_price'];
			$line['locprice']=$ol['local_price'];
			$line['num']=$ol['product_qty'];
			$line['date_purch']=strtotime($ol['date_order']);
			
			$order['line'][$k]=$line;
		   
		
		}

         // if($data['name']=='PO00170')die();
		//var_dump($order);
        //die();

	   addpurchorder($order);
	   
		$runnum=$runnum+1;
		
	 }
	 
	 ///$this->autoStockAll();
	   
   }
   
      public function getskustock($sku='')
   {
	   $data = $this->odooerp->readbySku($sku);
	   return $data[0]['qty_available']?$data[0]['qty_available']:0;
	  
   }
   
   ////从获取pos的订单并更新到数据库
   public function getposorder()
   {
	  
	  $data = $this->odooerp->_initializePos();
	  
	  $ids= $this->odooerp->getposorderids();
	  
	   
	   //var_dump($ids);
	   ////对于已经处理的订单不处理
	   foreach($ids as $k=> $id)
	   {
	    	$od= M('order')->where("ref like 'pos-%-".$id."'")->find();
            if($od)
			{
				unset($ids[$k]);
			}					
	   }
	    //echo "此次处理的IDS：<br>";
	    //var_dump($ids);

	  $order=$this->odooerp->getposorderinfo($ids);
	  $lines=array();   
	  $payids=array();
	  $goodsorder=array();  ///返回的商品订单数据
	  //var_dump($order);
	  //ksort($order);
	  foreach($order  as $k=> $o)
	  {
		  $lines=array_merge($lines,$o['lines']);
		  $payids=array_merge($payids,$o['statement_ids']);
		  $currorder['ref']=str_replace("订单","pos-",$o['pos_reference'])."-".$o['id'];
		  $currorder['channel_code']='pos';
		  $currorder['trade_pattern']='h1'; ///暂时设为暂时展销
		  $currorder['date_order']=$o['date_order']; ///数据时间
		  $currorder['buyer']= "pos".$o['id']."@posbuyer.com";
		  $currorder['seller']= "pos".$o['write_id'][0]."@posuser.com";
		  $currorder['receive_info']=$o['create_uid'][1].'||中国|重庆|重庆市|南岸区|'.$o['company_id'][1].$o['location_id'][0].'|400000';
		  $currorder['total_import_taxes']=0;
		  $currorder['amount_untaxed']=$o['amount_total'];
		  $currorder['amount_total']= $o['amount_total'];
		  $currorder['delivery_fee']= 0;
		  $currorder['buyer_reg_no']= "pos".$o['id']."@posbuyer.com";
		  $currorder['buyer_id_type']= 0; ///现场购买
		  $currorder['buyer_id_card']= ""; ///未留身份证
		  $currorder['warehouse']= "MD"; ///仓库-门店
		  $currorder['order_line']= array(); ///订单详情
		  $currorder['payment_line']= array(); ///支付信息
		  $currorder['state']=($o['state']=='paid')?1:0; ///订单状态
		  
		  $goodsorder[$o['id']]['order']=$currorder;
		  
	  }
	  ///获取POS orderline 包括产品sku这些
	  $orderline=$this->odooerp->getposorderlines($lines);
	  foreach($orderline  as $k=> $l)
	  {
		  $orderid=  $l['order_id'][0];
		  preg_match("/\[(P\d+)\](.+)/", $l['product_id'][1], $pd);
		  $goodsorder[$orderid]['order']['order_line'][]=array(
		     'sku'=> $pd[1],
		     'name'=>$pd[2],
		     'price'=>$l['price_unit'],
		     'num'=>$l['qty'],
		     'tax_fee'=>0,
		     'sub_total_untaxed'=> ($l['price_unit']*$l['qty']==$l['price_subtotal'])?$l['price_subtotal']:$l['price_unit']*$l['qty'],
		     'sub_total'=>($l['price_unit']*$l['qty']==$l['price_subtotal'])?$l['price_subtotal']:$l['price_unit']*$l['qty']
		  );
		  
	  }
	  
	   $paylines=$this->odooerp->getposorderpays($payids);
	   foreach($paylines as $k =>$l)
	   {
		   $orderid=  $l['pos_statement_id'][0];
		   if($l['journal_id'][0]==8) $paytype='cash';
		   if($l['journal_id'][0]==12) $paytype='weixin';
		   if($l['journal_id'][0]==10) $paytype='alipay';
		   if($l['journal_id'][0]==11) $paytype='unionpay';
		   $goodsorder[$orderid]['order']['payment_line'][]=array(
		   
		    'payment_account'=> $paytype,
		    'payment_type'=> $paytype,
		    'payamount'=> $l['amount'],
		  //  'create_date'=> $l['create_date'],
		    'payment_no'=> 'pos-orderid-'.$orderid.'-payid-'.$l['id']
		   
		   );
		   
		   
	   }
	   
	   foreach($goodsorder as $k =>$o)
	   {
		   //echo "from here:<pre>";
		   //var_dump($o);
		   if(!addOrder($o['order'],$msg)){
			//	var_dump($msg);
		   } 
	   }
  
  
	   return 'ok';
   
 
	  
  // var_dump($orderline);
	  
   }  

   
   public function test_upprice()
   {
	   ///改价
	   $modol=M('product_po');
	   //$_SESSION['currGOODSID']=7671;
	   if(!isset($_SESSION['currGOODSID']))$_SESSION['currGOODSID']=2175;
	   echo 'curr_id:'.$_SESSION['currGOODSID']."<br>";
	   $data=$modol->where("id>".$_SESSION['currGOODSID'])->limit(1)->find();
	   var_dump($data);
	   
	   $result=$this->goods_price_update($data['sku'],$data['ref_price']);
       $re=json_decode($result);
	   var_dump($result);
	   if($data&&$re->erp_sku_price_update_response->data)
	   {
		      			   
			   $_SESSION['currGOODSID']=$data['id'];
			   echo "next goods_id:".  $_SESSION['currGOODSID'];
		  	   echo '剩余'.$_SESSION['needle'].'等待进入下一个商品的价格修改。'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),300)</script><br>';

		   
	   }   

	   
   }
   public function goods_price_update($skuid='P0133802',$price='4.3')
   {
	    $this->__construct();
		//$modol=M('goods');
		//echo $skuid;
		$ds['username']=$this->username;
	    $ds['passwd']=$this->password;
		$ds['method']='erp.sku.price.update';
		$ds['code']=$skuid;
		$ds['price']=$price;
		var_dump($ds);
		$result=$this->post_json($this->url,$ds);
		var_dump($result);
		return $result;
		
	   
   }
   
   ////注册ERP的sku
   public function goods_reg($id=1)
   {
	   
		              // 首先开启session
        //$_SESSION['needle']=1170;
		if(isset($_SESSION['needle']))$_SESSION['needle']=$_SESSION['needle']-1;
	    $this->__construct();
		$modol=M('goods');
		$ds['username']=$this->username;
	    $ds['passwd']=$this->password;
		/*  税务信息获取
		$ds['skuList']=array('P0000053');
		$ds['method']='erp.hsTaxRate.get';
		$result=$this->post_json($this->url,$ds);
		
		var_dump($result);die(); */
		$ds['method']='erp.goods.add';

		
		$data=$modol->where("sku is null or sku =''")->limit(1)->find();
		
		
		if(!$data){echo "no date need to proccessed";die();} 
        $goods_id=$data['id'];
		$ds['code']=$data['earn13'];
		$ds['name']=$data['name'];
		//$ds['attr1_list']= $data['price'];
		
		$ds['lst_price']=$data['price'];
		$ds['cat_code']='002';
		//$supply_id=$this->get_supplyid_byearn13($data['earn13']);
		//echo "供应商：".$supply_id."<br>";
		$supply_id=$data['supply_id']?$data['supply_id']:'cqhqhsm';
		$ds['id_card']=$supply_id; ///供应商编码erp_supply_id
		$ds['brand_code']='SC2016';
		//echo "提交数据：";
		print_r($ds);
		$result=$this->post_json($this->url,$ds);
		//echo "<br>";
		
		$re=json_decode($result);
		var_dump($re);
		//echo "<br>";
	    //echo $re->erp_supplier_add_response->data;
	  ///回写供应商ID
      if($re->erp_goods_add_response->data)
	  {
		  $da['id']=$goods_id;
		  $da['erp_id']=$re->erp_goods_add_response->data->goods;
		  $da['sku']=$re->erp_goods_add_response->data->sku_list[0]->code;
		  $da['supply_id']=$supply_id;
		  $da['lastmodify']=time();
		  
		  //var_dump($da);
		  $modol->where('id='.$goods_id)->data($da)->save();
		  //echo "<br>saved goods_info <br>";
	  };
	  
	 //if($data&&$re->erp_goods_add_response->data)
	  // echo '剩余'.$_SESSION['needle'].'等待进入下一个商品的ERP注册。'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),300)</script><br>';
	  //if(!$re)
      	 //echo '接口错误5秒后重新刷新。'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),5000)</script><br>';	  
	   
   }
   
   
   
   public function get_supplyid_byearn13($en13)
   {
	  $model=M('spzl');
      $data=$model->where(' code ='.$en13)->find();
      //$supplier=M('suplier');
	  //$sup=$supplier->where("code = 'sc".$data['supply_id']."' ")->find();
      return 'sc'.$data['supply_id'];
   }
   
   public function ordersyn($goods=0)
   {
	   echo "test";
	   $this->__construct();

	 $goods=array (
		  'order' => 
		  array (
  'ref' => '2016101714513111',
  'channel_code' => 'hhr',
  'trade_pattern' => 'b1',
  'date_order' => '2016-10-17 14:16:16',
  'buyer' => '20@qq.com',
  'seller' => '532427264@qq.com',
  'receive_info' => '测试|17783067698|中国|重庆|重庆市|南岸区|重庆市南岸区学府大道33号交科院10栋|530200',
  'total_import_taxes' => 0,
  'amount_untaxed' => 0.01,
  'amount_total' => 0.01,
  'delivery_fee' => 0,
  'buyer_reg_no' => '2973738594@qq.com',
  'buyer_name' => '测试',
  'ship_code' => 'yto',
  'buyer_id_type' => '1',
  'buyer_id_card' => '450121199101144524',
  'order_line' => 
  array (
    0 => 
    array (
      'sku' => 'P0041417',
      'name' => '(保税)德国 Lavera 柠檬平衡洗发露200ml',
      'price' => 0.01,
      'num' => 1,
      'tax_fee' => 0,
      'sub_total' => 0.01,
      'sub_total_untaxed' => 0.01,
    ),
  ),
  'payment_line' => 
  array (
    0 => 
    array (
      'payment_account' => 'weixin',
      'payamount' => 0.01,
      'payment_no' => '4006202001201612142738343717',
    ),
  ),
  'discount' => 0,
  'ebpCode' => '50089609A8',
  'ship_code' => 'YTO',
),
		);
	var_dump($goods);echo "<br/><br/><br/>";
	$goods=array('order'=>array('ref'=>'2017042516058430'));
	$datastr=serialize($goods);
	//echo $datastr;
    //$datastr='a:1:{s:5:"order";a:19:{s:3:"ref";s:16:"2017042516601093";s:12:"channel_code";s:3:"b2b";s:13:"trade_pattern";s:2:"b1";s:10:"date_order";s:19:"2017-04-25 16:14:14";s:5:"buyer";s:12:"21214@qq.com";s:6:"seller";s:17:"2201848779@qq.com";s:12:"receive_info";s:160:"董晓犟|230206198505090717|13712500740|中国|重庆市|重庆市|南岸区|重庆市南岸区 翠湖山庄重庆市南岸区茶园新区南岸新行政中心";s:18:"total_import_taxes";s:6:"27.000";s:14:"amount_untaxed";s:7:"227.160";s:12:"amount_total";s:7:"254.160";s:12:"delivery_fee";s:5:"0.000";s:12:"buyer_reg_no";s:12:"21214@qq.com";s:10:"buyer_name";s:9:"董晓犟";s:13:"buyer_id_type";s:1:"1";s:13:"buyer_id_card";s:18:"230206198505090717";s:10:"order_line";a:1:{i:0;a:7:{s:3:"sku";s:9:" P0133629";s:4:"name";s:58:"德国today SHAMPOO COLOR & GLANZ 护色光泽洗发香波";s:5:"price";d:6.3099999999999996;s:3:"num";i:36;s:7:"tax_fee";s:6:"27.000";s:9:"sub_total";s:7:"254.160";s:17:"sub_total_untaxed";d:227.16;}}s:12:"payment_line";a:1:{i:0;a:3:{s:15:"payment_account";s:6:"baofoo";s:9:"payamount";d:254.16;s:10:"payment_no";s:16:"2017042516601093";}}s:7:"ebpCode";s:10:"50089609A8";s:9:"ship_code";s:3:"YTO";}}';
	
	$datastr='a:1:{s:5:"order";a:19:{s:3:"ref";s:16:"2017042516058430";s:12:"channel_code";s:3:"b2b";s:13:"trade_pattern";s:2:"b1";s:10:"date_order";s:19:"2017-04-25 16:37:41";s:5:"buyer";s:12:"21214@qq.com";s:6:"seller";s:17:"2201848779@qq.com";s:12:"receive_info";s:192:"陈弘	|310105196801222410|18622505705|中国|重庆|重庆市|九龙坡区|重庆市九龙坡区陈弘		重庆市九龙坡区高新区二郎科技城广播电视大学旁二郎·欣茂苑A栋";s:18:"total_import_taxes";s:6:"27.000";s:14:"amount_untaxed";s:7:"227.160";s:12:"amount_total";s:7:"254.160";s:12:"delivery_fee";s:5:"0.000";s:12:"buyer_reg_no";s:12:"21214@qq.com";s:10:"buyer_name";s:7:"陈弘	";s:13:"buyer_id_type";s:1:"1";s:13:"buyer_id_card";s:18:"310105196801222410";s:10:"order_line";a:2:{i:0;a:7:{s:3:"sku";s:8:"P0133626";s:4:"name";s:34:"德国 today 草本洗发露 500ml";s:5:"price";d:6.3099999999999996;s:3:"num";i:18;s:7:"tax_fee";s:6:"13.500";s:9:"sub_total";s:7:"127.080";s:17:"sub_total_untaxed";d:113.58;}i:1;a:7:{s:3:"sku";s:9:" P0133629";s:4:"name";s:58:"德国today SHAMPOO COLOR & GLANZ 护色光泽洗发香波";s:5:"price";d:6.3099999999999996;s:3:"num";i:18;s:7:"tax_fee";s:6:"13.500";s:9:"sub_total";s:7:"127.080";s:17:"sub_total_untaxed";d:113.58;}}s:12:"payment_line";a:1:{i:0;a:3:{s:15:"payment_account";s:6:"baofoo";s:9:"payamount";d:254.16;s:10:"payment_no";s:16:"2017042516058430";}}s:7:"ebpCode";s:10:"50089609A8";s:9:"ship_code";s:3:"YTO";}}';
   //$datastr='a:1:{s:5:"order";a:1:{s:3:"ref";s:16:"2017042516058430";}}';
   //echo $datastr;
	  $goods=unserialize($datastr);
	 
	  if(isset($goods['order']['total_import_taxes'])) $goods['order']['total_import_taxes']=(float)$goods['order']['total_import_taxes'];
	  if(isset($goods['order']['amount_untaxed'])) $goods['order']['amount_untaxed']=(float)$goods['order']['amount_untaxed'];
	  if(isset($goods['order']['amount_total'])) $goods['order']['amount_total']=(float)$goods['order']['amount_total'];
	  if(isset($goods['order']['delivery_fee'])) $goods['order']['delivery_fee']=(float)$goods['order']['delivery_fee'];
	  if(isset($goods['order']['order_line'][0]['tax_fee'])) $goods['order']['order_line'][0]['tax_fee']=(float)$goods['order']['order_line'][0]['tax_fee'];
	  if(isset($goods['order']['order_line'][0]['sub_total'])) $goods['order']['order_line'][0]['sub_total']=(float)$goods['order']['order_line'][0]['sub_total'];
	  if(isset($goods['order']['order_line'][0]['sub_total_untaxed'])) $goods['order']['order_line'][0]['sub_total_untaxed']=(float)$goods['order']['order_line'][0]['sub_total_untaxed'];
	  
	  if(isset($goods['order']['order_line'][1]['tax_fee'])) $goods['order']['order_line'][1]['tax_fee']=(float)$goods['order']['order_line'][1]['tax_fee'];
	  if(isset($goods['order']['order_line'][1]['sku'])) $goods['order']['order_line'][1]['sku']=trim($goods['order']['order_line'][1]['sku']);
	  if(isset($goods['order']['order_line'][1]['sub_total'])) $goods['order']['order_line'][1]['sub_total']=(float)$goods['order']['order_line'][1]['sub_total'];
	  if(isset($goods['order']['order_line'][1]['sub_total_untaxed'])) $goods['order']['order_line'][1]['sub_total_untaxed']=(float)$goods['order']['order_line'][1]['sub_total_untaxed'];
	  
	  if(isset($goods['order']['receive_info'])) $goods['order']['receive_info']=$this->strip2jsonstr($goods['order']['receive_info']);
	  $goods['order']['discount']=0;
	 $goods['method'] = 'erp.trade.add';
	 $goods['username'] = $this->username;
	 $goods['passwd'] = $this->password;
	 
	   var_dump($goods);
	  
	 $result=$this->post_json($this->url,$goods);
	 
     echo "<br>result:";
     var_dump($result);
	 echo "<br>";
   }
    public function strip2jsonstr($str)
	{
		
		$str=str_replace('	','',$str);
		$str=str_replace('·','',$str);
		return str_replace('"','',$str);
	}
	/**
	* ERP订单同步
	*/
	public function erpOrderSyn( $order_id = '') {
	    $this->__construct();
	    $where = array('erp_order_sync' => 0);
	    if( $order_id ) {
	    	$where = array('id' => $order_id);
	    }
	    $where['state'] = 1;
		$order_data = M('order')->where( $where )->field('id,ref,channel_code,trade_pattern,date_order,buyer,seller,receive_info,total_import_taxes,amount_untaxed,amount_total,delivery_fee,buyer_reg_no,buyer_name,buyer_id_type,buyer_id_card')->select();
		if( $order_data ) {
			foreach( $order_data as $key => $value ) {
				$order_line_data = M('order_line')->where(array('order_id' => $value['id']))->field('sku,name,price,num,tax_fee,sub_total,sub_total_untaxed')->select();
				//没有产品信息直接设置同步失败
				if( !$order_line_data ) {
					M('order')->where(array('order_id' => $value['id']))->save(array('erp_order_sync' => 1 , 'erp_sync_error_info' => '在本服务器没有检测到关联的订单商品存在'));
					continue;
				} else {
					//转换数据类型
					foreach( $order_line_data as $k => $v ) {
						$order_line_data[$k]['price'] = round( $v['price'] , 2);
						$order_line_data[$k]['tax_fee'] = round( $v['tax_fee'] , 2);
						$order_line_data[$k]['sub_total'] = round( $v['sub_total'] , 2);
						$order_line_data[$k]['sub_total_untaxed'] = round( $v['sub_total_untaxed'] , 2);
						$order_line_data[$k]['num'] = (int)$v['num'];
					}
				}
				$value['order_line'] = $order_line_data;
				//获取支付信息
				$order_pay_info = M('order_payment')->where(array('order_id' => $value['id']))->field('payment_account,payamount,payment_no')->select();
				//没有支付信息直接设置同步失败
				if( !$order_pay_info ) {
					M('order')->where(array('order_id' => $value['id']))->save(array('erp_order_sync' => 1 , 'erp_sync_error_info' => '在本服务器没有检测到关联的支付信息存在'));
					continue;
				} else {
					$config = D('Common/PaymentConfig')->getSettingConfig($value['id'] , $order_pay_info[0]['payment_account']);
					if( !$config ) {
						M('order')->where(array('order_id' => $value['id']))->save(array('erp_order_sync' => 1 , 'erp_sync_error_info' => '支付配置有问题，请联系技术解决'));
						continue;
					}
					//转换数据类型
					foreach( $order_pay_info as $k => $v ) {
						$order_pay_info[$k]['payamount'] = round( $v['payamount'] , 2);
					}
				}
				$value['payment_line'] = $order_pay_info;
				unset( $value['id'] );
				$value['ebpCode'] = $config['enterprise_code'];

				//数据类型转换
				$value['total_import_taxes'] = round( $value['total_import_taxes'] , 2 );
				$value['amount_untaxed'] = round( $value['amount_untaxed'] , 2 );
				$value['amount_total'] = round( $value['amount_total'] , 2 );
				$value['delivery_fee'] = round( $value['delivery_fee'] , 2 );
				//==== end ====//
				$result=$this->post_json($this->url,array('order' => $value ,'method' =>'erp.trade.add' , 'username' => $this->username , 'passwd' => $this->password ));
				$result = json_decode( $result , true );
				//判断是否同步成功
				if( isset( $result['erp_trade_add_response']['rsp'] ) &&  $result['erp_trade_add_response']['rsp'] == 'succ') {
					M('order')->where(array('ref' => $value['ref']))->save(array('erp_order_sync' => 2 , 'erp_sync_error_info' => ''));
				} else {
					$msg = '请联系ERP技术解决';
					if( isset( $result['erp_trade_add_response']['error_response']['msg'] ) ) {
						$msg = '错误代码：' . $result['erp_trade_add_response']['error_response']['msg'];
					}
					M('order')->where(array('ref' => $value['ref']))->save(array('erp_order_sync' => 1 , 'erp_sync_error_info' => $msg));
					if( $order_id ) return false;
				}
			}
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 微信清关
	 */
	public function clearance( $order_id = '') {
		
		$where = array('o.trade_pattern' => array('IN' , array('b1' , 'b2')));
		if( $order_id == '' ) {
			$where['o.wx_order_sync'] = 0;
		} else {
			$where['o.id'] = $order_id;
		}
	    $where['o.state'] = 1;
		$order_data = M('order')->alias('o')->join('__ORDER_PAYMENT__ op ON op.order_id = o.id')->where( $where )->field('op.payment_no AS transaction_id,o.ref AS out_trade_no,o.ref_extend,o.id,op.payment_account,op.payamount')->select();
		if( $order_data ) {
			foreach( $order_data as $key => $value ) {
				$config = D('Common/PaymentConfig')->getSettingConfig( $value['id'] , $value['payment_account'] );
				if( !$config ) {
					M('order')->where(array('order_id' => $value['id']))->save(array('wx_order_sync' => 1 , 'wx_order_error_info' => '支付配置有问题，请联系技术解决'));
					continue;
				}
				$pay_type = $value['payment_account'];
				$object_name = '\\Api\\Extend\\Payment\\' . ucfirst( $pay_type ); //组合空间命名
		        $object = new $object_name( $config );
		        $result = $object->clearance( $value );
		        if( !$result && $order_id) return false;
		        M('order')->where(array('ref' => $value['out_trade_no'] ))->save(array('wx_order_sync' => $result['state'] , 'wx_order_error_info' => $result['msg']));
		        if( $result['status'] === false && $order_id ) {
		        	return false;
		        }
			}
			return true;
		} else {
			return false;
		}
		
	}

	/**
	 * 微信清关查询
	 */
	public function clearanceSelect() {
		$order_data = M('order')->alias('o')->join('__ORDER_PAYMENT__ op ON op.order_id = o.id')->where(array('o.wx_order_sync' => 2 , 'o.state' => 1 ,'o.trade_pattern' => array('IN' , array('b1' , 'b2'))))->field('o.alipay_out_request_nos,op.payment_account,op.payment_no AS transaction_id,o.id')->select();
		if( $order_data ) {
			foreach( $order_data as $key => $value ) {
				$config = D('Common/PaymentConfig')->getSettingConfig( $value['id'] , $value['payment_account'] );
				if( !$config ) continue;
		        $order_id = $value['id'];
				$object_name = '\\Api\\Extend\\Payment\\' . ucfirst( $value['payment_account'] ); //组合空间命名
		        $object = new $object_name( $config );
		        $result = $object->clearanceSelect( $value );
		        if( isset( $result[ 'status' ] ) ) {
		        	M('order')->where(array('id' => $order_id))->save(array('wx_order_sync' => $result['state'] , 'wx_order_error_info' => $result['msg']));
		        }
			}
		}
	}
     
    /**
     * 退款查询
     */
    public function refunQuery() {
    	$order_data = M('order')->alias('o')->join('__ORDER_PAYMENT__ op ON op.order_id = o.id')->where(array('state' => 4))
    							->field('o.*,op.payment_account,op.payment_no')->select();
    	if( $order_data ) {
    		foreach( $order_data as $key => $value ) {
    			$config = D('Common/PaymentConfig')->getSettingConfig( $value['id'] , $value['payment_account'] );
				if( !$config ) continue;
		    	$object_name = '\\Api\\Extend\\Payment\\' . ucfirst( $value['payment_account'] ); //组合空间命名
				$object = new $object_name( $config );
				$object->refundQuery( $value );
			}
		}
    }
	
	public function test()
	{
		$orderModel=M('order');
		$this->odooerp->_initialize();
		
		$ids=$this->odooerp->getorderids();
		
		$idx=array_slice($ids,0,5);
		$orders=$this->odooerp->readorder($idx);
		foreach($orders as $k=>$o)
		{
			
		  var_dump($o);
		  $currorder=array();	
		  if($o['channel_id'][0]==3){$channel_code='wx';}
		  
		  
		  $currorder['ref']=$o['ref'];
		  $currorder['channel_code']=$channel_code;
		  $currorder['trade_pattern']=$o['trade_pattern']; ///暂时设为暂时展销
		  $currorder['date_order']=$o['date_order']; ///数据时间
		  $currorder['buyer']= $o['buyer_name'];
		  $currorder['seller']= $o['seller_id'][1];
		  $currorder['receive_info']=$o['receive_info'];
		  $currorder['total_import_taxes']=$o['total_import_taxes'];
		  $currorder['amount_untaxed']=$o['amount_untaxed'];
		  $currorder['amount_total']= $o['amount_total'];
		  $currorder['delivery_fee']= $o['delivery_fee'];
		  $currorder['buyer_reg_no']= $o['buyer_reg_no'];
		  $currorder['buyer_id_type']= $o['buyer_id_type'];
		  $currorder['buyer_id_card'] = $o['buyer_reg_no'];
		  $currorder['ship_code'] = $o['ship_code'];
		  $currorder['ship_no'] = $o['ship_no'];
		  $currorder['order_line']= array(); ///订单详情
		  $currorder['payment_line']= array(); ///支付信息
		  $currorder['warehouse_id']= $o['warehouse_id'][0]; ///支付信息
		  $currorder['state']=1; ///订单状态
			

			$orderlines=$this->odooerp->readorderline($o['order_line']);
			
			foreach($orderlines as $k=>$l)
			{
			 preg_match("/\[(P\d+)\](.+)/", $l['product_id'][1], $pd);
		     $currorder['order_line'][]=array(
		     'sku'=> $pd[1],
		     'name'=>$pd[2],
		     'price'=>$l['price'],
		     'num'=>$l['num'],
		     'tax_fee'=>$l['tax_fee'],
		     'sub_total_untaxed'=> $l['sub_total_untaxed'],
		     'sub_total'=>$l['sub_total']
		    );
		  
		  
		    }
		
			
			///支付单
			if($o['payment_id'][0]==26)$paytype='weixin';
			if($o['payment_id'][0]==26)$paytype='weixin';
			if($o['payment_id'][0]==26)$paytype='weixin';
			if($o['payment_id'][0]==26)$paytype='weixin';
			
			if($paytype=='') {
				echo $o['payment_id'][0]."----".$o['payment_id'][1];
                die();
				}
			$currorder['payment_line'][]=array(	   
		     'payment_account'=> $paytype,
		     'payment_type'=> $paytype,
		     'payamount'=> $o['amount_total'],
		     'payment_no'=> $o['payment_no']
		   
		   );
		   
		   
		    echo "<pre>";
			var_dump($currorder);
			$paytype='';
			$channel_code='';
			addOrder($currorder,$msg);
			 echo "<pre>";
			var_dump($msg);
			die();
			
		}
	}
	/*
		  获取ERP发货单的订单号
		  未完成
		
		*/
		
	public function getshipno()
	{
		/*
		  获取ERP发货单的订单号
		*/
		 $orderModel=M('order');
		 $this->odooerp->_initializeB();
		 $ids=$this->odooerp->getpickingids2();
		 $pagesize=5;
		 $count=count($ids);
		 ///分页
		 if(is_numeric($_GET['page']))
		 {
			 $_SESSION['shoptmppage']=$_GET['page'];
			 
		 }
		 if(!isset($_SESSION['shoptmppage']))
		 {
			 $_SESSION['shoptmppage']=1;
			 $start=0;
			 }
	     else
		 {
			 $start=($_SESSION['shoptmppage']-1)*$pagesize;
		 }
		 
		 
		 
		 $pages=floor($count/$pagesize);
		 echo "当前第".$_SESSION['shoptmppage']."/".$pages."页.<br/>";
		 echo $start;
		 $ids=array_slice($ids,$start,$pagesize);
		 echo count($ids);
		 
		 echo "<pre>";
		$i=0;
		$orderModel->startTrans();
		foreach($ids as $k=>$id)
		{
			
			 $data=$this->odooerp->readstockpicking($id); 
			 var_dump($data['ec_order']);
			 //var_dump($data['ship_code'].$data['ship_no']);
			 $o=$orderModel->where(array('ref'=>$data['ec_order']))->find();
			 
			 var_dump($o);
			 $i++;
		}
		$orderModel->commit();
		if(count($ids)==$pagesize)
		{
			$_SESSION['shoptmppage']=$_SESSION['shoptmppage']+1;
			echo '<br/>waiting for next refresh :'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),5000)</script><br>';
			
			die(); 
		}
		
		
	}
	
	/*
	   更新H仓的分拣信息
	   H4stockpickingsyn
	*/
	public function H4stockpickingsyn()
	{
		
	   $runnum=0;
	   $maxnum=5;
	  
		$order=M('stock_picking');
	    ///存储到临时数值
	    $this->odooerp->_initializeH();
        if(count($_SESSION['TMP_PICKIDS_4HP'])==0||!isset($_SESSION['TMP_PICKIDS_4HP']))
		{
			 $ids=$this->odooerp->getpickingids();
			 $_SESSION['TMP_PICKIDS_4HP']=$ids;
		}else
		{
			$ids=$_SESSION['TMP_PICKIDS_4HP'];
		}
	 

	    $idstring=implode(",",$ids);
		$eids=$order->field('flag')->where("pick_type>0 and flag in (".$idstring.")")->select();
	    $eds=array();
		foreach($eids as $e)
		{
			$eds[]=(int)$e['flag'];
		}
		 
  
		$ids=array_diff($ids,$eds);
		 //var_dump($ids);

        //die();
	    echo "stockpicking :".count($ids)."  to process.<br>";
		//$ids=array();
		///$ids[]=1018;
		
		//var_dump($ids);
	   foreach($ids as $k =>$id)
	   {
		 if($runnum>$maxnum)
		 {
			echo 'waiting for next refresh 3:'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),5000)</script><br>';
			die(); 
		 }
		 $data=$this->odooerp->readstockpicking($id); 
		 
		
		 if($data['id']<=0) 
		 {
			 var_dump($data);
			 echo "123".$data['id']."id=".$id;
			 die();
		 }
		 $order=array();
		$order['pick_id']='pick-4H-'.$data['id'];
	    $order['oper']=$data['write_uid'][1];
		echo "process :".$data['origin']." .<br>";
		if(strpos($data['origin'],"||")>0)
		{
			$to=explode($data['origin']);
			$data['origin']=$to[1];
		}
	    $order['poname']=$data['origin'];
	    $order['date']=strtotime($data['date']);
	    $order['state']=$data['state'];
	    $order['location_id']=$data['location_id'][0];
	    $order['location_dest_id']=$data['location_dest_id'][0];
	    $order['qty']=$data['to_do'];
	    $order['qty_done']=$data['have_do'];
	    $order['pick_type']=$data['picking_type_id'][0];
	    $order['stock']='4H';
	    $order['flag']=$data['id'];
		
		
		 $lines=$data['move_lines'];
		 if(count(lines)==0){echo "cant find lines.<br>";die();} 
		 $linedata=$this->odooerp->readstockmovelines($lines);
		 
		 $order['lines']=array();
		    foreach($linedata as $i =>$l)
			{
				$line=array();
				preg_match("/\[(P\d+)\](.+)/", $l['product_id'][1], $pd);
				$line['sku']=$pd[1];
				$line['date']=strtotime($l['write_date']);
				$line['location_id']=$l['location_id'][0];
				$line['location_dest_id']=$l['location_dest_id'][0];
				$line['procure_method']=$l['procure_method'];
				$line['state']=$l['state'];
				$line['picking_id']=$order['pick_id'];
				$line['qty']=$l['product_qty'];
				$order['lines'][$i]=$line;
			}
		
	
		 addstockpicking($order,$msg);

		 $runnum++;
		 //var_dump($order);
		
		 
	   }
	    if(count($_SESSION['TMP_PICKIDS'])<$runnum) exit();
	    echo  'waiting for next refresh2:'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),3000)</script><br>';
	}
	
	
	/*
	   更新H仓的盘存信息
	*/
	public function H4pancunsyn()
	{
		///盘存相当于分拣操作-统一到分拣操作
		$runnum=0;
	    $maxnum=3;
	  
		$order=M('stock_picking');
		$this->odooerp->_initializeH();
	    ///存储到临时数值
	    if(count($_SESSION['TMP_PICKIDS_P_4H'])==0||!isset($_SESSION['TMP_PICKIDS_P_4H']))
		{
			 $ids=$this->odooerp->getpancunids();
			 //var_dump($ids);
			 $_SESSION['TMP_PICKIDS_P_4H']=$ids;
		}else
		{
			$ids=$_SESSION['TMP_PICKIDS_P_4H'];
		}
		 
		$idstring=implode(",",$ids);
		///盘存的pick type设置为0
		$eids=$order->field('flag')->where("pick_type=0 and stock='4H' and flag in (".$idstring.")")->select();
	    $eds=array();
		foreach($eids as $e)
		{
			$eds[]=(int)$e['flag'];
		}
		 
  
		$ids=array_diff($ids,$eds);
		 //var_dump($ids);
        // $ids=array();
		// $ids[]=8;
        //die();
		
	    echo "pancun :".count($ids)."  to process.<br>";
	 
		 foreach($ids as $k =>$id)
	   {
		 if($runnum>$maxnum)
		 {
			echo 'waiting for next refresh 3:'.'<script type="text/javascript"> function refresh(){location.href=location.href;window.location.reload();};setTimeout(refresh(),5000)</script><br>';
			die(); 
		 }
		 $data=$this->odooerp->readpancun($id);
		
		 if($data['id']<=0) 
		 {
			 var_dump($data);
			 echo "123".$data['id']."id=".$id;
			 die();
		 }
		 $order=array();
		$order['pick_id']='pancun-4H-'.$data['id'];
	    $order['oper']=$data['write_uid'][1];
		echo "process :".$data['origin']." .<br>";
		if(strpos($data['origin'],"||")>0)
		{
			$to=explode($data['origin']);
			$data['origin']=$to[1];
		}
		
	    $order['poname']=$data['origin'];
	    $order['date']=strtotime($data['date']);
	    $order['state']=$data['state'];
	    $order['location_id']=$data['location_id'][0];
	    $order['location_dest_id']=$data['location_dest_id'];
	    $order['qty']=$data['to_do'];
	    $order['qty_done']=$data['have_do'];
	    $order['pick_type']=0;
	    $order['stock']='4H';
	    $order['flag']=$data['id'];
		 
		 
		 $lines=$data['move_ids'];
		 if(count(lines)==0){echo "cant find lines.<br>";die();} 
		 $linedata=$this->odooerp->readstockmovelines($lines);
		 
		 $order['lines']=array();
		    foreach($linedata as $i =>$l)
			{  
				$line=array();
				preg_match("/\[(P\d+)\](.+)/", $l['product_id'][1], $pd);
				$line['sku']=$pd[1];
				$line['date']=strtotime($l['write_date']);
				$line['location_id']=$l['location_id'][0];
				$line['location_dest_id']=$l['location_dest_id'][0];
				$line['procure_method']=$l['procure_method'];
				$line['state']=$l['state'];
				$line['picking_id']=$order['pick_id'];
				$line['qty']=$l['product_qty'];
				$order['lines'][$i]=$line;
			}
        ///add here
		echo "add started.";
	
		addstockpicking($order);
		
		$runnum++;
		//die();
	   }
	}
	
	/*
	
	获取备案信息
	*/
	public function refreshskuinfo(){
		
		 
		 $this->odooerp->_initialize();
		 $ids= $this->odooerp->getskubeianids();
		 $total=count($ids);
		 $pagesize=5;
		 $page=isset($_GET['page'])?$_GET['page']:1;
		 echo ">>>>";
		 echo $page."<<<";
		 
		 echo ">>>>";
		 echo var_dump($_GET)."<<<<br>";
		 $start=($page-1)*$pagesize;
		 $ids_read=array_slice($ids,$start,$pagesize);
		 $skulist= $this->odooerp->readskubeian($ids_read);
		 
		 $skuinfo=M('sku_info');
		 foreach($skulist as $k=>$sku)
		 { 
			$data=array(); 
			preg_match("/\[(\d+)\](.+)/", $sku['hs_code'][1], $pd);
			$data['sku']=$sku['sku'];
			$data['goods_spec']=$sku['goods_spec'];
			$data['eshop_ent_code']=$sku['eshop_ent_code'];
			$data['eshop_ent_name']=$sku['eshop_ent_name'];
			$data['declare_unit']=$sku['declare_unit'][1];
			$data['origin_country_code']=$sku['origin_country_code'][1];
			$data['hs_code']=$pd[1];
			$data['hs_code_name']=$pd[2];
			$data['goods_name']=$sku['goods_name'];			 
			$data['state']=$sku['state'];
			// $data=$sku;
			if($skuinfo->where(array('sku'=>$sku['sku']))->find())
			  {
				  $skuinfo->save($data);
			  }else
			  {
				  $skuinfo->add($data);
			  }
			  $goods=array();
			  $goods['sku']=$sku['sku'];
			  $goods['tax_no']=$pd[1];
			
			M('goods')->where("sku='".$goods['sku']."'")->save($goods);
			///更新goods 表sku hs编码
			
			
			 
		 }
		//echo count($ids_read);
		if(count($ids_read)==$pagesize)
		{
			$nextpage=$page+1;
		echo "next page is ".$nextpage."<br>";
		$nexturl= U('ShopSiteApi/runapi',array('apiid'=>$_GET['apiid'],'page'=>$nextpage));
		echo '<script type="text/javascript"> function refresh(){location.href="'.$nexturl.'";};setTimeout(refresh(),5000)</script><br>';	
		}
		
		 //var_dump($skulist);
	} 
}

